package cn.pzhuweb.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import org.testng.annotations.Test;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Yancy xiao
 * @create 2022-11-15 9:03
 */
public class DruidUtil {
    //1.声明数据源
    private static DataSource ds = null;

    //2.初始化
    static {
        // 读取配置文件信息
        InputStream inputStream = DBUtil.class.getClassLoader().getResourceAsStream("druid.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //3.提供共有方法得到数据源
    public static DataSource getDs() {
        return ds;
    }

    //4.提供公共方法得到连接
    public static Connection getConnection() {
        try {
            return ds.getConnection();//从连接池中得到连接
        } catch (SQLException e) {
            e.printStackTrace();//连接池没有可用连接
            return null;
        }

    }

    @Test
    public void test() throws SQLException {
        for (int i = 0; i < 10; i++) {
            System.out.println(getDs().getConnection());
        }
    }
}
